from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from rest_framework.parsers import JSONParser
from .models import Task, Project
from .serializers import ProjectSerializer


def dashboard(request):
    """Display main information, provide a way to reach rest"""
    tasks = Task.objects.order_by('-created_at')[:5]
    context = {'latest_task_list': tasks}
    return render(request, 'storage/index.html', context)


@csrf_exempt
def project_list(request):
    if request.method == 'GET':
        projects = Project.objects.all()
        serializer = ProjectSerializer(projects, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method  == 'POST':
        data = JSONParser().parse(request)
        serializer = ProjectSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)
